package org.jrpc.core;

import org.jrpc.base.*;
import org.jrpc.client3.JrpcClient;
import org.jrpc.client3.JrpcClientManage;
import org.jrpc.core.factory.JRpcDefinitionPostProcessor;
import org.jrpc.core.factory.JrpcConfiguration;
import org.jrpc.core.registry.ZooKeeperServiceInfoManage;
import org.jrpc.core.registry.ZooKeeperServiceRegistryAndDiscovery;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import java.util.Set;
import java.util.UUID;

import static java.util.Collections.emptySet;

/**
 * Created by chenyuncong on 2018/7/19.
 */
//@ComponentScan("com.atguigu.ext")
@Configuration
public class SpringJrpcAutoConfiguration {

    private String host;
    private int port;
    private String zkAddress;

    private String jrpcName="jrpc";

//    @Autowired
//    private JrpcConfiguration jrpcConfiguration;


//    @ConditionalOnClass(ConfigurationPropertySources.class)
    @Bean
    public JRpcDefinitionPostProcessor getJRpcDefinitionPostProcessor(Environment environment,IClientManage iClientManage){
        Set<String> packagesToScan = environment.getProperty("spring", Set.class, emptySet());
//        RpcClient client=new RpcClient("127.0.0.1", 9080);
        //实例化注入的是服务信息集合，使用netty去链接他们 todo
        //配置信息类型 对于包扫描的路径 todo
        JRpcDefinitionPostProcessor jRpcDefinitionPostProcessor=new JRpcDefinitionPostProcessor(packagesToScan,iClientManage);
        return jRpcDefinitionPostProcessor;
    }

    @Bean
    public IClientManage getIClientManage(ServiceInfoManage serviceInfoManage){
        return new JrpcClientManage(serviceInfoManage);
    }

    //实例化zk注册与发现
    @Bean
    public ServiceDiscoveryAndRegistry getServiceDiscoveryAndRegistry(JrpcConfiguration jrpcConfiguration,ServiceInfoManage serviceInfoManage){
//        ServiceInfo serviceInfo = new ServiceInfo(UUID.randomUUID().toString(),jrpcConfiguration.getServiceName(),
//                jrpcConfiguration.getHost(),Integer.parseInt(jrpcConfiguration.getPort()),jrpcConfiguration.getStatus());
//        return new ZooKeeperServiceRegistryAndDiscovery(jrpcConfiguration.getAddress(),serviceInfo);

        return new ZooKeeperServiceRegistryAndDiscovery(jrpcConfiguration,serviceInfoManage);
    }

    //实例化zk管理服务信息
    @Bean
    public ServiceInfoManage getServiceInfoManage(){
        return new ZooKeeperServiceInfoManage();
    }

//    @Bean
//    public IClient iClient(JrpcConfiguration jrpcConfiguration){
//        return new JrpcClient(jrpcConfiguration);
//    }

    //实例化配置信息
    @Bean
    public JrpcConfiguration getJrpcConfiguration(){
        return new JrpcConfiguration();
    }
    //启动重连
//    @Bean
//    public ConnectionListener connectionListener(IClient iClient){
//        return new ConnectionListener(iClient);
//    }

//    public AnnotationScanner getAnnotationScanner(){
//        return new AnnotationScanner();
//    }
}
